package com.foolishbird.sdk.system;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.text.format.Formatter;


import com.foolishbird.sdk.utils.IoUtils;
import com.foolishbird.sdk.utils.WL;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;



public final class DeviceInfo {

    private static final String TAG = DeviceInfo.class.getSimpleName();

    private DeviceInfo() {
    }

    /**
     * 获取手机内存大小
     *
     * @param context 上下文
     * @return
     */
    public static String getTotalMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.totalMem);
    }

    /**
     * 获取当前可用内存大小s
     *
     * @param context
     * @return
     */
    public static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.availMem);
    }

    /**
     * CPU最大频率
     *
     * @return
     */
    public static String getMaxCpuFreq() {
        return readFileContent("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq") + "Hz";
    }

    // 获取CPU最小频率（单位KHZ）
    public static String getMinCpuFreq() {
        return readFileContent("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq") + "Hz";
    }

    /**
     * 实时获取CPU当前频率（单位KHZ）
     *
     * @return
     */
    public static String getCurCpuFreq() {
        return readFileContent("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq") + "Hz";
    }

    //CPU名字
    public static String getCpuName() {
        InputStreamReader fileReader = null;
        FileInputStream fileStream = null;
        BufferedReader bufferedReader = null;
        try {
            fileStream = new FileInputStream("/proc/cpuinfo");
            fileReader = new InputStreamReader(fileStream, "utf-8");
            bufferedReader = new BufferedReader(fileReader);
            String text = bufferedReader.readLine();
            String[] array = text != null ? text.split(":\\s+", 2) : new String[0];
            return array.length >= 1 ? array[1] : "unkown";
        } catch (UnsupportedEncodingException e) {
            WL.e(TAG, "getCpuName ---> UnsupportedEncodingException");
        } catch (FileNotFoundException e) {
            WL.e(TAG, "getCpuName ---> FileNotFoundException");
        } catch (IOException e) {
            WL.e(TAG, "getCpuName ---> IOException");
        } finally {
            IoUtils.closeSilently(bufferedReader);
            IoUtils.closeSilently(fileReader);
            IoUtils.closeSilently(fileStream);
        }
        return "unkown";
    }

    /**
     * 获取手机安装的应用信息（排除系统自带）
     *
     * @param context
     * @return
     */
    public static String getAllApp(Context context) {
        StringBuilder result = new StringBuilder();
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        if(packages != null){
            for (PackageInfo i : packages) {
                if ((i.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                    result.append(i.applicationInfo.loadLabel(context.getPackageManager()).toString());
                    result.append(",");
                }
            }
        }

        String resultStr = result.toString();

        if (TextUtils.isEmpty(resultStr)) {
            return "null";
        } else {
            return resultStr.substring(0, Math.max(resultStr.length() - 1, 0));
        }
    }

    /**
     * 是否安装了微信
     * @param context
     * @return
     */
    public static boolean isInstalledWeChat(Context context) {
        WL.d(TAG, "isInstalledWeChat ------->");
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo info : packages) {
            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                if (TextUtils.equals("com.tencent.mm", info.applicationInfo.packageName)) {
                    return true;
                } else if (TextUtils.equals("com.tencent.mm", info.applicationInfo.processName)) {
                    return true;
                } else {
                    String appName = info.applicationInfo.loadLabel(pm).toString().toLowerCase();
                    if (TextUtils.equals(appName, "wechat") || TextUtils.equals(appName, "微信")) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 是否安装了云闪付APP
     * @param context
     * @return
     */
    public static boolean isInstalledUnionPay(Context context){
        WL.d(TAG, "isInstalledUnionPay ------->");
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo info : packages) {
            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                if (TextUtils.equals("com.unionpay", info.applicationInfo.packageName)) {
                    return true;
                } else if (TextUtils.equals("com.unionpay", info.applicationInfo.processName)) {
                    return true;
                } else {
                    String appName = info.applicationInfo.loadLabel(pm).toString().toLowerCase();
                    if (TextUtils.equals(appName, "云闪付")) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 获取手机MAC地址
     *
     * @param context
     * @return
     */
    public static String getMacAddress(Context context) {
//        String macAddress = null;
//        Context applicationContext = context.getApplicationContext();
//        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//            WifiManager wifiMgr = (WifiManager)applicationContext.getSystemService(Context.WIFI_SERVICE);
//            WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
//            if (null != info) {
//                macAddress = info.getMacAddress();
//            }
//        }
//
//        if(!TextUtils.isEmpty(macAddress)){
//            return macAddress;
//        }
//
//        StringBuffer buf = new StringBuffer();
//        NetworkInterface networkInterface = null;
//        try {
//            networkInterface = NetworkInterface.getByName("eth1");
//            if (networkInterface == null) {
//                networkInterface = NetworkInterface.getByName("wlan0");
//            }
//            if (networkInterface == null) {
//                return "02:00:00:00:00:00";
//            }
//            byte[] addr = networkInterface.getHardwareAddress();
//
//            if(addr == null){
//                return "02:00:00:00:00:00";
//            }
//
//            for (byte b : addr) {
//                buf.append(String.format("%02X:", b));
//            }
//
//            if (buf.length() > 0) {
//                buf.deleteCharAt(buf.length() - 1);
//            }
//            macAddress = buf.toString();
//        } catch (SocketException e) {
//            e.printStackTrace();
//            macAddress = "02:00:00:00:00:00";
//        }
//        return macAddress;
        String mac = getMac1(context);
        if (!TextUtils.isEmpty(mac)) {
            return mac;
        }
        mac = getMac2();
        if (!TextUtils.isEmpty(mac)) {
            return mac;
        }
        mac = getMac3();
        if (!TextUtils.isEmpty(mac)) {
            return mac;
        }
        mac = getMac4();
        if (!TextUtils.isEmpty(mac)) {
            return mac;
        }
        return "02:00:00:00:00:00";
    }

    private static String getMac1(Context ctx) {
        WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        if (info != null) {
            return "02:00:00:00:00:00".equals(info.getMacAddress())?"":info.getMacAddress();
        }
        return null;
    }

    public static String getMac2() {
        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str;) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return "02:00:00:00:00:00".equals(macSerial)?"":macSerial;
    }

    /**
     * 根据IP地址获取MAC地址
     *
     * @return
     */
    public static String getMac3() {
        String strMacAddr = null;
        try {
            // 获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        } catch (Exception e) {

        }

        return "02:00:00:00:00:00".equals(strMacAddr)?"":strMacAddr;
    }

    /**
     * 获取移动设备本地IP
     *
     * @return
     */
    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            // 列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {// 是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();// 得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {

            e.printStackTrace();
        }
        return ip;
    }

    /**
     * 通过网络接口取
     *
     * @return
     */
    public static String getMac4() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0"))
                    continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }



    private static final String readFileContent(String filePath) {
        StringBuilder builder = new StringBuilder();
        InputStream inputStream = null;
        InputStreamReader reader = null;
        try {
            String[] args = {"/system/bin/cat", filePath};
            ProcessBuilder cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            inputStream = process.getInputStream();
            reader = new InputStreamReader(inputStream, "utf-8");
            char[] buffer = new char[24];
            int lenght = -1;
            while ((lenght = reader.read(buffer)) != -1) {
                builder.append(buffer, 0, lenght);
            }
        } catch (UnsupportedEncodingException ex) {
            WL.e(TAG, "getMaxCpuFreq ---> UnsupportedEncodingException");
            builder.delete(0, builder.length());
            builder.append("N/A");
        } catch (IOException ex) {
            WL.e(TAG, "getMaxCpuFreq ---> IOException");
            builder.delete(0, builder.length());
            builder.append("N/A");
        } finally {
            IoUtils.closeSilently(reader);
            IoUtils.closeSilently(inputStream);
        }
        return builder.toString().trim();
    }
}
